﻿using Devonline.Core;
using Devonline.MessageQueue;

namespace Benchmark;

public class MessageQueue(IMessageQueueService messageQueueService)
{
    private const string _subscriptionName = "benchmark";
    private const string _topic = "persistent://public/default/benchmark";
    private readonly IMessageQueueService _messageQueueService = messageQueueService;
    private readonly List<string> _messages = [];

    /// <summary>
    /// 启动消息队列客户端
    /// </summary>
    public Task StartAsync() => _messageQueueService.StartAsync();
    /// <summary>
    /// 停止消息队列客户端
    /// </summary>
    /// <returns></returns>
    public async Task StopAsync() => await _messageQueueService.StopAsync();
    /// <summary>
    /// 发出随机的消息
    /// </summary>
    /// <returns></returns>
    public async Task PublicAsync() => await _messageQueueService.PublishAsync<string>(_topic, KeyGenerator.GetStringKey());
    /// <summary>
    /// 订阅消息
    /// </summary>
    /// <returns></returns>
    public async Task SubscribeAsync(Func<List<string>, Task> whenFinished) => await _messageQueueService.SubscribeAsync(_topic, _subscriptionName, async message =>
    {
        if (message == "Unsubscribe")
        {
            await whenFinished(_messages);
        }
        else
        {
            _messages.Add(message);
        }

        await Task.CompletedTask;
    });

    /// <summary>
    /// 批量发出随机的消息
    /// </summary>
    /// <param name="count">执行次数</param>
    /// <returns></returns>
    public async Task ParallelPublicAsync(int count)
    {
        Console.WriteLine($"the benchmark of {nameof(MessageQueue)} will parallel run {nameof(PublicAsync)} {count} times!");
        var startTime = DateTime.Now;
        await Parallel.ForAsync(0, count, async (x, y) => await PublicAsync());
        await _messageQueueService.PublishAsync<string>(_topic, "Unsubscribe");
        Console.WriteLine($"the benchmark of {nameof(MessageQueue)} parallel run {nameof(PublicAsync)}: " + startTime.GetTimeDetail());
        await Task.CompletedTask;
    }
}